import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View,
    Button,
    TextInput,
    FlatList,
    RefreshControl,
    ActivityIndicator,
    Alert,
    AsyncStorage
} from 'react-native';
import {
    observer,
    inject //注入
} from 'mobx-react'
import Toast, {DURATION} from 'react-native-easy-toast'
import DataRepository, {FLAG_STORAGE} from '../expand/dao/DataRepository';
const URL = 'https://api.github.com/search/repositories?q=';
const QUERY_STR = '&sort=stars';

import ScrollableTabView ,{ScrollableTabBar, DefaultTabBar} from 'react-native-scrollable-tab-view';
import RepositoryCell from '../common/RepositoryCell';
import LanguageDao, {FLAG_LANGUAGE}from '../expand/dao/LanguageDao';

import NavigationBar from '../common/NavigationBar';
import ProjectModel from "../common/model/ProjectModel";

import Utils from '../common/util/Utils';
import FavoriteDao from '../expand/dao/FavoriteDao';

var favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular);

@inject('appState')
@observer
export default class PopularPage extends Component {
    constructor(props){
        super(props);
        this.dataRepository = new DataRepository(FLAG_STORAGE.flag_popular);
        this.languageDao = new LanguageDao(FLAG_LANGUAGE.flag_key)
        this.state = {
	        result: '暂未数据',
            languages: []
        }
    }
    loadData(){
        this.languageDao.fetchData()
            .then(result=>{
                this.setState({
                    languages: result
                })
            })
            .catch(error=>{
                console.log(error)
            })
    }
    // componentWillMount(){
    //     AsyncStorage.getAllKeys((error, arrays)=>{console.log(arrays)})
    // }
    componentDidMount(){
        this.loadData();
    }
    render(){
        let content = this.state.languages.length > 0 ?
            <ScrollableTabView
                tabBarInactiveTextColor="mintcream"
                tabBarActiveTextColor="white"
                tabBarUnderlineStyle={{backgroundColor: '#e7e7e7', height: 2}}
                tabBarBackgroundColor="#2196f3"
                locked={true}
                renderTabBar={()=><ScrollableTabBar/>}
                initialPage={0}
            >
                {this.state.languages.map((result, i, arr)=>{
                    let lan= arr[i];
                    return lan.checked ? <PopularTab key={i} tabLabel={lan.name} {...this.props}></PopularTab> : null;
                })}
            </ScrollableTabView> : null;
        return (
            <View style={styles.container}>
                <NavigationBar
                    statusBar={{
                        backgroundColor:'#2196f3'
                    }}
                    title={'最热'}
                    style = {{
                        backgroundColor: '#2196f3'
                    }}
                />
                {/*<Text>{`我是全局Store:${this.props.appState.userMsg}`}</Text>*/}
                {content}
            </View>
        )
    }
}

class PopularTab extends Component {
    constructor(props){
        super(props);
        this.dataRepository = new DataRepository();
        this.state = {
            result: '',
            dataSource: [],
            isLoading:false,
            favoriteKeys: []
        }
    }
    componentWillMount(){
        this.loadData();
    }

    /**
     * 更新Project Item 收藏(Favorite)的状态
     */
    flushFavoriteState(){
        let projectModels = [];
        let items = this.items;
        for(let i=0,len=items.length;i<len;i++) {
            projectModels.push(new ProjectModel(items[i], Utils.checkFavorite(items[i], this.state.favoriteKeys)));
            //projectModels.push(new ProjectModel(items[i], true));
        }
        this.updateState({
            isLoading: false,
            dataSource: projectModels
        })
    }
    updateState(dic){
        if(!this)return;
        this.setState(dic)
    }
    /**
     * 获取用户所有收藏的数据
     * */
    getFavoriteKeys(){
        favoriteDao.getFavoriteKeys()
            .then(keys=>{
                if(keys) {
                    this.updateState({
                        favoriteKeys:keys
                    })
                }
                this.flushFavoriteState();
            })
            .catch(e=>{
                this.flushFavoriteState();
            })
    }
    loadData(){
        this.setState({
            isLoading: true
        })
        let url = URL+ this.props.tabLabel + QUERY_STR;
        this.setState({
            result: '数据加载中...'
        })
        this.dataRepository
            .fetchRepository(url)
            .then(result=>{
                this.items = result && result.items ? result.items : result ? result : [];
                // this.setState({
                //     dataSource: this.items,
                //     isLoading: false
                // })
                //this.flushFavoriteState();
                this.getFavoriteKeys();
                if (result && result.update_data && !this.dataRepository.checkData(result.update_data)) {
                    this.refs.toast.show('数据过时', 500);
                    return this.dataRepository.fetchNetRepository(url);
                }else {
                    this.refs.toast.show('显示缓存数据');
                }
            })
            .then(items=>{
                if(!items || items.length ===0) return;
                this.items = items;
                //this.flushFavoriteState();
                // this.setState({
                //     dataSource: this.items
                // })
                this.getFavoriteKeys();
                this.refs.toast.show('显示网络数据');
            })
            .catch(error=>{
                this.setState({
                    result: JSON.stringify(error)
                })
                this.updateState({
                    isLoading: false
                })
            })
    }
    genIndicator(){
        return <View style={styles.indicatorContainer}>
            <ActivityIndicator
                style={styles.indicator}
                color={'red'}
                size = {'large'}
                animating={true}
            />
            {/*<Text>正在加载更多</Text>*/}
        </View>
    }

    /**
     * favoriteIcon的单击回调函数
     * @param item
     * @param isFavorite
     */
    onFavorite(item, isFavorite){
        if(isFavorite) {
            favoriteDao.saveFavoriteItem(item.id.toString(), JSON.stringify(item))
        } else {
            favoriteDao.removeFavoriteItem(item.id.toString());
        }
    }
    _renderItem(projectModel) {
        return <RepositoryCell
            projectModel={projectModel}
            onSelect={()=>this.onSelect(projectModel)}
            onFavorite={(item, isFavorite)=>this.onFavorite(item, isFavorite)}
        />
    }
    onSelect(data){
        this.props.navigation.navigate('RepositoryDetail',{dataFather: data})
    }
    render(){
        return (
            <View style={{flex: 1}}>
                <FlatList
                    data={this.state.dataSource}
                    renderItem={(data)=>this._renderItem(data)}
                    //个性定制
                    refreshControl={
                        <RefreshControl
                            title={"Loading"}
                            colors={['#2196f3']}
                            refreshing={this.state.isLoading}
                            onRefresh={()=>{
                                this.loadData(true);
                            }}
                        />
                    }
                   /* ListFooterComponent = {()=>this.genIndicator()}*/
                    //优化组件
                    getItemLayout={(data, index) => (
                        // 120 是被渲染 item 的高度 ITEM_HEIGHT。
                        {length: 120, offset: 120 * index, index}
                    )}
                  /*  onEndReached = {()=>{
                        this.loadData()
                    }}*/
                />
                <Toast
                    ref="toast"
                    position='top'
                    positionValue={200}
                />
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1
    }
})